#!BPY
"""
Name: 'TPhysics'
Blender: 245
Group: 'Export'
Tooltip: 'TPhysics mesh exporter'
"""

from __future__ import with_statement
import Blender
import bpy

from random import randint


class Vector3:
    def __init__(self,ix,iy,iz):
        self.x = ix
        self.y = iy
        self.z = iz
        
    def Write(self, out):
        out.write("x = \"")
        out.write(str(self.x))
        out.write("\" y = \"")
        out.write(str(self.y))
        out.write("\" z = \"")
        out.write(str(self.z))
        out.write("\"")

    x = 0
    y = 0
    z = 0

class UV:
    def __init__ (self, iu,iv):
        self.u = iu
        self.v = iv

    def Write(self, out):
        out.write("u = \"")
        out.write(str(self.u))
        out.write("\" v = \"")
        out.write(str(self.v))
        out.write("\"")                

    u = 0
    v = 0
    
class Vertex:

    def __init__(self):
        self.position = Vector3(0,0,0)    
        self.normal = Vector3(0,0,0)
        self.uv = UV(0,0)

    
    def Write(self, out):
        out.write("<vertex>\n")
        out.write("<position ")
        self.position.Write(out)
        out.write("/>\n")                
        out.write("<normal ")
        self.normal.Write(out)
        out.write("/>\n")
        out.write("<texcoord0 ")
        self.uv.Write(out)
        out.write("/>\n")                                
        out.write("</vertex>\n")

    position = Vector3(0,0,0)    
    normal = Vector3(0,0,0)
    uv = UV(0,0)

class Face:

    def __init__(self, iv1, iv2, iv3):
        self.v1 = iv1
        self.v2 = iv2
        self.v3 = iv3

    def Write(self, out):
        out.write("<face v1 = \"")
        out.write(str(self.v1))
        out.write("\" v2 = \"")
        out.write(str(self.v2))
        out.write("\" v3 = \"")
        out.write(str(self.v3))
        out.write("\"/>\n")
    
    v1 = 0
    v2 = 0
    v3 = 0

class SubMesh:

    def __init__(self, iname, imaterial):
        self.material = imaterial
        self.name = iname
        self.faces = []

    def Write(self, out):
        out.write("<submesh name = \"")
        out.write(self.name)
        out.write("\" material = \"")
        out.write(self.material)
        out.write("\" facecount = \"")
        out.write(str(len(self.faces)))
        out.write("\">\n")
        for f in self.faces:
            f.Write(out)
        out.write("</submesh>\n")

    faces = []
    material = "material"
    name = "name"

vertices = []
submeshes = []


#Vertex comparison
def CompVertex(v1, v2):
    if v1.position.x == v2.position.x and v1.position.y == v2.position.y and v1.position.z == v2.position.z:
        if v1.normal.x == v2.normal.x and v1.normal.y == v2.normal.y and v1.normal.z == v2.normal.z:
            if v1.uv.v == v2.uv.v and v1.uv.u == v2.uv.u:
                return True
    return False
            
#Add new vertex to global list and return index, remove duplicated vetices.
def AddVertex(vert):
    index = -1
    for i in xrange(len(vertices)):
        if CompVertex(vertices[i],vert) == True:
            index = i
            break
    if index == -1:
        vertices.append(vert)
        index = len(vertices) - 1
    return index
    
#main export part
def WriteMeshFile(fname):
    with file(fname,"w") as out:
        out.write("<mesh>\n")

        #write sub meshes
        for sm in submeshes:
            sm.Write(out)

        #write out vertices
        out.write("<vertices count = \"")
        out.write(str(len(vertices)))
        out.write("\" position = \"true\" normal = \"true\" texture_coords = \"1\" >\n")
        
        for v in vertices:
            v.Write(out)
                
        out.write("</vertices>\n")

        out.write("</mesh>\n")



#export mesh data from blender objects
def ExportMesh(filepath):
    sce = bpy.data.scenes.active
    ob = sce.objects.active
    mesh = ob.getData(mesh=1)
    
    if len(mesh.materials) != 0:
        for mat in mesh.materials:
            submeshes.append(SubMesh(mat.getName(),mat.getName()))
    else:
        submeshes.append(SubMesh("material","material"))
    
    for face in mesh.faces:
        subMesh = submeshes[face.mat]
        indices = []
        vertNum = 0
        for vert in face.v:
        
            smVertex = Vertex()

            smVertex.position.x = vert.co.x
            smVertex.position.y = vert.co.z
            smVertex.position.z = vert.co.y
            
            smVertex.normal.x = face.no.x
            smVertex.normal.y = face.no.z
            smVertex.normal.z = face.no.y

            if mesh.faceUV == True:
                smVertex.uv.u = face.uv[vertNum][0]
                smVertex.uv.v = face.uv[vertNum][1]

            indices.append(AddVertex(smVertex))
            
            vertNum = vertNum + 1

        smFace = Face(indices[0],indices[1],indices[2])
        subMesh.faces.append(smFace)

    WriteMeshFile(filepath)

Blender.Window.FileSelector(ExportMesh, "Export")

#Test
##for mat in xrange(0,3):    
##        submeshes.append(SubMesh("mm %(#)d"%{"#":mat},"mm"))
##
##for sm in xrange(0,3):
##    print "smesh %(#)d" % {"#":sm}
##    for face in xrange(0,10):
##        indices = []
##        for vert in xrange(0,3):
##            smVertex = Vertex()
##
##            smVertex.position.x = randint(0,100)
##            smVertex.position.y = randint(0,100)
##            smVertex.position.z = randint(0,100)
##            
##            smVertex.normal.x = randint(0,100)
##            smVertex.normal.y = randint(0,100)
##            smVertex.normal.z = randint(0,100)
##
##            smVertex.uv.u = randint(0,100)
##            smVertex.uv.v = randint(0,100)
##
##            indices.append(AddVertex(smVertex))
##
##        smFace = Face(indices[0],indices[1],indices[2])
##        submeshes[sm].faces.append(smFace)
##        print "face %(#)d %(len)d" % {"#":face,"len":len(submeshes[sm].faces)}
##
##WriteMeshFile("object.xml")
